package com.qxzn.app.medicalhealth.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.ContactsBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.MedicineRemindBean;
import com.qxzn.app.medicalhealth.R;
import com.qxzn.app.medicalhealth.R2;
import com.qxzn.app.medicalhealth.adapter.FamilyMedicalRecordsContentAdapter;
import com.qxzn.app.medicalhealth.adapter.FamilyMedicalRecordsHeadAdapter;
import com.qxzn.app.medicalhealth.util.ScalePageTransformer;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.SharePreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 吃药提醒
 */
public class TakeMedicalRemindActivity extends BaseActivity {

    @BindView(R2.id.vp_head)
    ViewPager vp_head;
    @BindView(R2.id.vp_content)
    ViewPager vp_content;
    private FamilyMedicalRecordsHeadAdapter headAdapter;
    private List<ContactsBean.DataBean> headList = new ArrayList<>();
    private List<List<MedicineRemindBean.DataBean.ResultBean>> contentList = new ArrayList<>();
    private FamilyMedicalRecordsContentAdapter contentAdapter;
    private int pageSize = 10;
    private int currentPosition = 0;

    @Override
    protected int initLayout() {
        return R.layout.activity_family_cases;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("吃药提醒");
        iv_right.setVisibility(View.VISIBLE);
        iv_right.setImageResource(R.mipmap.logo);
        iv_right.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
//        for (int i = 0; i < 10; i++) {
//            headList.add(new ContactsBean.DataBean());
//        }
        vp_head.setPageTransformer(true, new ScalePageTransformer());
        headAdapter = new FamilyMedicalRecordsHeadAdapter(this, this);
        headAdapter.setData(headList);
        //在设置数据之后必须得调setAdapter，否则会导致Transform初始状态不正常
        vp_head.setAdapter(headAdapter);
        vp_head.setCurrentItem(currentPosition, true);
        vp_head.setOffscreenPageLimit(headList.size() - 1);
        vp_head.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                vp_content.setCurrentItem(position, true);
                currentPosition = position;
                AppUtil.showLog("位置2：" + position);
                if (contentList.get(position).size() == 0) {
//                    getMedicineRemindTime(position, headList.get(0).getMemName(), 1);
                    getMedicineRemindTime(position, headList.get(position).getMemName(), 1);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        vp_content.setPageTransformer(true, new ScalePageTransformer());
        contentAdapter = new FamilyMedicalRecordsContentAdapter(this, TakeMedicalRemindActivity.class.getSimpleName());
        contentAdapter.setData(contentList);
        //在设置数据之后必须得调setAdapter，否则会导致Transform初始状态不正常
        vp_content.setAdapter(contentAdapter);
        vp_content.setCurrentItem(currentPosition, true);
        if (contentList.size() - 1 > 0) {
            vp_content.setOffscreenPageLimit(contentList.size() - 1);
        }
        vp_content.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                vp_head.setCurrentItem(position, true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        refreshData();
    }

    private void addMySelfData() {
        headList.clear();
        ContactsBean.DataBean self = new ContactsBean.DataBean();
        self.setMemName(SharePreferenceUtil.getUserName(this));
        self.setMemRemarks("我");
        self.setAge(SharePreferenceUtil.getAge(this));
        self.setHeadportrait(SharePreferenceUtil.getPortrait(this));
        headList.add(self);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.ll_item) {
            vp_head.setCurrentItem((int) view.getTag(), true);
        } else if (view.getId() == R.id.iv_right) {
            startActivityForResult(new Intent(this, ChooseUserActivity.class).putExtra("title", ChooseUserActivity.remindTitle), 1);
        }
    }

    private void getContacts() {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"device_id\":\"" + SharePreferenceUtil.getDeviceId(this) + "\",\"username\":\"" + SharePreferenceUtil.getUserName(this) + "\"}");
        Call<ContactsBean> call = HttpRequest.getService().getContacts(body);
        call.enqueue(new Callback<ContactsBean>() {
            @Override
            public void onResponse(Call<ContactsBean> call, Response<ContactsBean> response) {
                ContactsBean bean = response.body();
                if (bean != null) {
                    List<ContactsBean.DataBean> deviceList = bean.getData();
                    if (deviceList != null && deviceList.size() > 0) {
                        headList.addAll(deviceList);
                        headAdapter.notifyDataSetChanged();
                        contentList.clear();
                        for (int i = 0; i < headList.size(); i++) {
                            contentList.add(new ArrayList<>());
                        }
                        contentAdapter.notifyDataSetChanged();
                        getMedicineRemindTime(currentPosition, headList.get(currentPosition).getMemName(), 1);
                        return;
                    }
                }
                if (bean != null && bean.getCode() != 200 && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(TakeMedicalRemindActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(TakeMedicalRemindActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<ContactsBean> call, Throwable t) {
                AppUtil.showToast(TakeMedicalRemindActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void getMedicineRemindTime(int position, String username, int page) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("device_id", SharePreferenceUtil.getDeviceId(this));
        jsonObject.put("username", username);
        jsonObject.put("current_page", page);
        jsonObject.put("num", pageSize);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        Call<MedicineRemindBean> call = HttpRequest.getService().getMedicineRemindTime(body);
        call.enqueue(new Callback<MedicineRemindBean>() {
            @Override
            public void onResponse(Call<MedicineRemindBean> call, Response<MedicineRemindBean> response) {
                MedicineRemindBean bean = response.body();
                if (bean != null && bean.getCode() == 200) {
                    if (bean.getData() != null) {
                        List<MedicineRemindBean.DataBean.ResultBean> remindList = bean.getData().getResult();
                        if (remindList != null && remindList.size() > 0) {
                            contentList.set(position, remindList);
                            contentAdapter.notifyDataSetChanged();
                        }
                    }
                    return;
                }
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(TakeMedicalRemindActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(TakeMedicalRemindActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<MedicineRemindBean> call, Throwable t) {
                AppUtil.showToast(TakeMedicalRemindActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void refreshData() {
        addMySelfData();
        headAdapter.notifyDataSetChanged();
        getContacts();
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == 3) {//修改吃药提醒的刷新
            refreshData();
        }
    }

}
